#!/usr/bin/env python

# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Demo Identity Provider Attribute API."""

from google.appengine.ext import webapp
from django.utils import simplejson as json
import logging

from lib import utils #@UnresolvedImport
from lib import authz #@UnresolvedImport
from lib import http #@UnresolvedImport
import model

__author__ = "Maciej Machulak"
__maintainer__ = "Maciej Machulak"
__email__ = "mmachulak@google.com"

__copyright__ = "Copyright 2011, Google Inc."
__license__ = "Apache License 2.0"
__version__ = "0.1"
__status__ = "Prototype"

class AttributeTokenHandler(webapp.RequestHandler):

    @authz.api_authz_required('streetaddress_read')
    def get(self, path):
      
      if path is not None or len(path) > 0:
      
        id = path #@ReservedAssignment
        
        logging.debug('request for street address with id %s' % id)
        
        address = model.StreetAddress.all().filter('id = ', id).get()
        if address is None:
          logging.error('street address could not be found')
          self.response.set_status(404)
          return
        else:
          logging.debug('street address found')
          user = self.user
          application = self.application
          
          access_token = utils.random()
          logging.debug('generated access token %s' % access_token)
          
          attribute_authorization = model.AttributeAuthorization(
                     access_token = access_token,
                     requester = application,
                     street_address = address,
                     user = user)
          attribute_authorization.put()
          logging.debug('authorization for retrieving attribute has been created and stored')
          
          token_response = {}
          token_response['access_token'] = access_token
          self.response.headers[http.Header.content_type] = http.ContentType.urlencoded
          self.response.out.write(json.dumps(token_response))            
